package cn.slt.controller;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.slt.util.String2Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;

import cn.slt.domian.MD_ClassDSID;
import cn.slt.domian.MD_ObjDSID;
import cn.slt.domian.MD_libraryDSID;
import cn.slt.service.MD_ObjDSIDService;
import cn.slt.service.MD_classDSIDService;
import cn.slt.service.MD_libraryDSIDService;
import cn.slt.util.ImportExcelUtil;

@Controller
public class UploadController {
	@Autowired
	private MD_ObjDSIDService serviceobj;
	@Autowired
	private MD_classDSIDService serviceclass;
	@Autowired
	private MD_libraryDSIDService servicelib;

	@ResponseBody
	@RequestMapping(value = "upload_lzd", method = { RequestMethod.GET, RequestMethod.POST })
	public String upload(HttpServletRequest request) throws Exception {
		System.out.println("Upload start ");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		String words = null;
		boolean mark = false;
		InputStream in = null;
		List<List<Object>> listob = null;
		MultipartFile file = multipartRequest.getFile("file");
		if (file.isEmpty()) {
			return "Data error or update unsucessfully!";
			// throw new Exception("文件不存在！");

		}
		in = file.getInputStream();
		listob = new ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());
		in.close();

		// upload wancheng
		System.out.println(listob);
		String name = "FX_ST_RAIN_H";
		// System.out.println(serviceclass.getdsCode(name));
		List<MD_ObjDSID> mdObjDSIDs = new ArrayList<MD_ObjDSID>();
		List<MD_ClassDSID> md_ClassDSIDs = new ArrayList<MD_ClassDSID>();
		List<MD_libraryDSID> md_libraryDSIDs = new ArrayList<MD_libraryDSID>();
		for (int i = 1; i < listob.size(); i++) {
			mark = true;
			List<Object> lo = listob.get(i);
			System.out.println("col size" + lo.size());

			if (lo.size() == 6) {
				MD_ObjDSID t = new MD_ObjDSID();

				t.setDsName(lo.get(3).toString().toUpperCase());
				t.setBeizhu(lo.get(4).toString());
				t.setComments(lo.get(5).toString());
				System.out.println("comments" + t.getComments());
				mark = serviceobj.updateobj(t);
				// if(!mark) return "2";

				System.out.println(t.toString());
			} else if (lo.size() == 5) {
				MD_ClassDSID t = new MD_ClassDSID();

				t.setDsName(lo.get(2).toString().toUpperCase());
				t.setKeywords(lo.get(3).toString());
				t.setBeizhu(lo.get(4).toString());

				mark = serviceclass.updateclass(t);
				// if(!mark) return "2";

				System.out.println(t.toString());

			} else {
				Date date;
				MD_libraryDSID t = new MD_libraryDSID();
				t.setDsName(lo.get(1).toString().toUpperCase());
				t.setStandname(lo.get(2).toString());
				t.setBuildUnit(lo.get(3).toString());
				t.setStaff(lo.get(4).toString());
				t.setMangUnit(lo.get(5).toString());
				t.setMangStaff(lo.get(6).toString());
				// t.setDsType(lo.get(7).toString());
				String2Date string2Date = new String2Date();
				date = string2Date.string2date(lo.get(7).toString());

				System.out.println("timeString" + lo.get(7).toString());
				System.out.println("timeDate" + date);
				t.setStartTime(date);
				// date=string2Date.string2date(lo.get(9).toString());
				// t.setEndTime(date);
				t.setKeywords(lo.get(8).toString());

				t.setBeizhu(lo.get(9).toString());
				t.setAttention(lo.get(10).toString());
				t.setUseconstr(lo.get(11).toString());
				t.setSeclevl(lo.get(12).toString());
				t.setOtherconstr(lo.get(13).toString());
				t.setExchangeEnv(lo.get(14).toString());
				t.setService(lo.get(15).toString());

				mark = servicelib.updatelib(t);
				// if(!mark) return "2";

				System.out.println(t.toString());
			}
		}
		// return JSONArray.toJSONString(listob);
		// return JSONArray.toJSONString(mdObjDSIDs);
		if (mark == true)
			words = "Upload success and update database successfully!";
		else
			words = "Data error or update unsucessfully!";
		return words;
	}

//	@ResponseBody
	@RequestMapping(value = "upload_pipei", method = { RequestMethod.GET, RequestMethod.POST })
	public String pipeiUpload(HttpServletRequest request,Model model) throws Exception {
		 StringBuilder sb=new StringBuilder();   
		 String string="123";
		 List<MD_ClassDSID> listclass=new ArrayList<MD_ClassDSID>();
		List<MD_ObjDSID >listobj=new ArrayList<MD_ObjDSID>();
		model.addAttribute("result1", listclass);
		model.addAttribute("result2", listobj);
		
	
		
		
		System.out.println("Upload start ");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		int tables = 0;
		int suctables = 0;
		int columns = 0;
		int sucolumns = 0;
		int cnt = 0; // cnt就是没有更新成功的条数
		String words = null;
		boolean mark = false;
		InputStream in = null;
		List<List<Object>> listob = null;
		
		MultipartFile file = multipartRequest.getFile("file");
		if (file.isEmpty()) {
			return "/uploadresult";
			// throw new Exception("文件不存在！");

		}
		in = file.getInputStream();
		listob = new ImportExcelUtil().getAllByExcel(in, file.getOriginalFilename());
		in.close();
		String res = "更新失败 ： " + "</br>";
		for (List<Object> listo : listob) {
			String r = "";
			if (listo.get(0).equals("supdscode")) {
				continue;
			}
			boolean flag = false;
			if (listo.get(0).equals("")) {
				r=r+"表 ：  "+"</br>";
				tables++;
				// System.out.println("tables");
				MD_ClassDSID table = new MD_ClassDSID();
				if(listo.get(1).equals("")) continue;
				System.out.println(listo.get(1));
				table.setDsCode(Integer.parseInt(listo.get(1).toString()));
				table.setDsName((String) listo.get(2));
				table.setBeizhu((String) listo.get(3));
				table.setKeywords((String) listo.get(4));
				// System.out.println(listo.get(3) + (String)listo.get(3));
				if (table.getBeizhu().equals("") && table.getKeywords().equals("")) {
					flag = false;
					listclass.add(table);
				} else {
					flag = serviceclass.updateclass(table);
				}

				if (flag == true)
					suctables++;
			} else {
				   columns++;
				if(columns==1)
				{
					r=r+"字段 ：   "+"</br>";
				}
				
				// System.out.println(r);
				MD_ObjDSID clums = new MD_ObjDSID();
		//		if(listo.get(0).equals("")) continue; //下次出问题就加上这行
				clums.setSupDsCode(Integer.parseInt(listo.get(0).toString()));
				clums.setDsCode(Integer.parseInt(listo.get(1).toString()));
				clums.setDsName((String) listo.get(2));
				clums.setBeizhu((String) listo.get(3));
				clums.setComments((String) listo.get(4));

				if (clums.getBeizhu().equals("") && clums.getComments().equals("")) {
					flag = false;
					listobj.add(clums);
				} else {
					flag = serviceobj.updateobj(clums);
				}

				if (flag == true)
					sucolumns++;
			}
			// System.out.println(flag);
			if (flag == false) {
				for (Object lis : listo) {
					r += lis + "  ";
				}

			}

			if (flag == false) {
				res += r + "<br>";
			}

		}
		words = "提交表数量:     " + tables + "   字段数量:    " + columns + "   " + "<br>" + "更新成功表数量     " + suctables
				+ " 更新成功字段数量     " + sucolumns + "<br>" + res;
		
//		return words;
		model.addAttribute("tables",tables);
		model.addAttribute("columns", columns);
		model.addAttribute("suctables", suctables);
		model.addAttribute("sucolumns", sucolumns);
		System.out.println(listclass.size());
		System.out.println(listob.size());
		return "/uploadresult";

		// upload wancheng

	}
}
/*
 * public String getUpFileMessage(HttpServletResponse response,
 * HttpServletRequest request,String path) { String fileName = null; String
 * upFileMessage = ""; String name; try { String tempFileName = "tempName";
 * 
 * File f1 = new File(path , tempFileName);
 * 
 * FileOutputStream o = new FileOutputStream(f1);
 * 
 * InputStream in = request.getInputStream();
 * 
 * byte b[] = new byte[10000];
 * 
 * int n;
 * 
 * while ((n = in.read(b)) != -1) { o.write(b, 0, n);
 * 
 * }
 * 
 * o.close();
 * 
 * in.close();
 * 
 * RandomAccessFile random = new RandomAccessFile(f1, "r");
 * 
 * int second = 1;
 * 
 * String secondLine = null;
 * 
 * while (second <= 2) { secondLine = random.readLine(); second++; }
 * 
 * int position = secondLine.lastIndexOf("=");
 * 
 * fileName = secondLine.substring(position + 2, secondLine.length() - 1);
 * 
 * byte cc[] = fileName.getBytes("ISO-8859-1");
 * 
 * fileName = new String(cc);
 * 
 * 
 * random.seek(0);
 * 
 * long forthEndPosition = 0;
 * 
 * int forth = 1;
 * 
 * while ((n = random.readByte()) != -1 && (forth <= 4)) { if (n == '\n') {
 * forthEndPosition = random.getFilePointer(); forth++; }
 * 
 * } File f2 = new File(path , fileName);
 * 
 * RandomAccessFile random2 = new RandomAccessFile(f2, "rw");
 * 
 * random.seek(random.length());
 * 
 * long endPosition = random.getFilePointer();
 * 
 * long mark = endPosition;
 * 
 * int j = 1;
 * 
 * while ((mark >= 0) && (j < 6)) { mark--; random.seek(mark); n =
 * random.readByte();
 * 
 * if (n == '\n') { endPosition = random.getFilePointer(); j++; } }
 * random.seek(forthEndPosition); long startPoint = random.getFilePointer();
 * 
 * while (startPoint < endPosition - 1) { n = random.readByte();
 * random2.write(n); startPoint = random.getFilePointer();
 * 
 * }
 * 
 * random2.close();
 * 
 * random.close();
 * 
 * f1.delete(); name = fileName; upFileMessage = fileName +
 * " Successfully UpLoad"; return upFileMessage;
 * 
 * } catch (Exception exp) { if (fileName != null) { upFileMessage = fileName +
 * "  上传失败"; return upFileMessage;
 * 
 * } else { upFileMessage = "上传失败"; return upFileMessage;
 * 
 * }
 * 
 * } }
 */
